// pages/garbageSearch/garbageSearch.js
const TianKey = 'e1826a74e2286bc44a4072f4b3ed4859'
const recorderManger = wx.getRecorderManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isNewList:false,//控制搜索垃圾组件的显示隐藏
    isShow:false,//控制清空按钮的是否隐藏
    searchVal:"",
    maxlength:10,
    searchedGarbage:{},
    hotList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.hotSearch()
    this.initBaiduYuyinAccessToken()
  },
  searchInput(event){
    // console.log(event)
    this.data.searchVal = event.detail.value
    if(this.data.searchVal){
      this.setData({
        isShow:true
      })
    }else{
      this.setData({
        isShow:false
      })
    }
  },
  searchGarbage(){
    wx.showLoading({
      title: '搜索中'
    })
    wx.request({
      url: `https://api.tianapi.com/txapi/lajifenlei/index?key=${TianKey}&word=${this.data.searchVal}&mode=1`,
      success:(res)=>{
        console.log(res)
        if(res.data.newslist && res.data.code === 200){
          this.setData({
            isNewList:true,
            searchedGarbage:res.data.newslist[0]
          })
        }else{
          wx.showModal({
            confirmText:'确定',
            confirmColor:'#576B95',
            title:'错误',
            content:res.data.msg
          })
        }
        wx.hideLoading()
      },
      fail:(err) => {
        wx.showModal({
          confirmText:'确定',
          confirmColor:'#576B95',
          title:'错误',
          content:err.message
        })
      }
    })
  },
  clear(){
    this.setData({
      searchVal:"",
      isShow:false
    })
  },
  hotSearch(){
    const ary = []
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: `https://api.tianapi.com/txapi/hotlajifenlei/index?key=${TianKey}`,
      success:(res) => {
        // console.log(res)
        res.data.newslist.forEach((item) => {
          if(item.index >= 1000){
            ary.push(item)
          }
        })
        this.setData({
          hotList:ary
        })
      },
      fail:(err) => {
        wx.showModal({
          confirmText:'确定',
          confirmColor:'#576B95',
          title:'错误',
          content:err.message
        })
      }
    })
    wx.hideLoading()
  },
  onClick(event){
    // console.log(event)
    const dataset = event.currentTarget.dataset
    let markName = ""
    if(dataset.type === 0){
      markName = '可回收物'
    }else if(dataset.type === 1){
      markName = '有害垃圾'
    }else if(dataset.type === 2){
      markName = '厨余垃圾(湿)'
    }else{
      markName = '干垃圾'
    }
    wx.showModal({
      confirmText:'确定',
      confirmColor:'#576B95',
      title:markName,
      content:dataset.name,
      showCancel:false
    })
  },
  //初始化语音识别
  initBaiduYuyinAccessToken(){
    const baiduAccessToken = wx.getStorageSync('access_token')
    if(baiduAccessToken == undefined || baiduAccessToken == ""){
      this.getBaiduYuyinAccessToken()
    }else{
      //access_token的获取时间
      let time = wx.getStorageSync('time')
      let currentTime = new Date().getTime()
      let timeNum = parseInt((currentTime - time)/1000/60/60/24)
      if(timeNum > 28){
        //如果access_token有效期过了，重新调用云函数获取
        this.getBaiduYuyinAccessToken()
      }
    }
  },
  //获取access_token
  getBaiduYuyinAccessToken(){
    wx.cloud.callFunction({
      name:'baiduAccessToken'
    })
    .then((res) => {
      // console.log(res);
      wx.setStorageSync('access_token', res.result.access_token)
      wx.setStorageSync('time', new Date().getTime())
    })
    .catch((err) => {
      console.log(err)
    })
  },
  //录音前检测scope.record授权情况，即检测是否被允许使用麦克风
  startRecordHandle(){
    wx.getSetting({
      success:(res) => {
        console.log(res);
        // console.log(res.authSetting['scope.address']);
        const scopeRecord = res.authSetting['scope.record']
        //已授权
        if(scopeRecord){
          this.record()
        }else{
          //如果没有授权，弹出窗口询问是否允许使用麦克风
          wx.authorize({
            scope: 'scope.record',
            success:(res) => {
              wx.showToast({
                title: '可以使用语音识别功能哟！',
              })
            },
            fail:(err) => {
              console.log('授权失败');
              wx.showModal({
                title: '没有权限',
                content: '体验该功能需要您授权功能权限，请前往设置开启',
              })
            }
          })

        }
      }
    })
  },
  handleTouchStart(){
    this.startRecordHandle()
  },
  handleTouchEnd(){
    // console.log(3);
    recorderManger.stop()
    this.stopEvent()
  },
  record(){
    const options = {
      duration: 30000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//通道数
      encodeBitRate: 48000,
      format:'aac'
    }
    //开始录音
    recorderManger.start(options)
    recorderManger.onStart((res) => {
      console.log('开始录音');
      wx.showLoading({
        title: '识别中...',
      })
    })
    
  },
  stopEvent(){
    recorderManger.onStop((res) => {
      console.log(res)
      const baiduAccessToken = wx.getStorageSync('access_token')
      const fileSize = res.fileSize
      const tempFilePath = res.tempFilePath
      let format = 'pcm'
      if(tempFilePath){
        format = tempFilePath.substring(tempFilePath.lastIndexOf('.') + 1);
      }
      const fs = wx.getFileSystemManager()
      fs.readFile({
        filePath:tempFilePath,
        encoding:'base64',
        success:(res) => {
          const base64 = res.data
          // console.log(res.data);
          wx.request({
            url: 'https://vop.baidu.com/pro_api',
            method:'post',
            data:{
              format:format,
              rate:16000,
              channel:1,
              cuid:'baidu_workshop',
              token:baiduAccessToken,
              dev_pid:80001,
              speech:base64,
              len:fileSize  
            },
            header:{
              'Content-Type':'application/json'
            },
            success:(res) => {
              console.log(res);
              if(res.data.result){
                let text = res.data.result[0].replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\。|\，|\！|\；|\>|\/|\?]/g,"")
                this.data.searchVal = text
                wx.hideLoading()
                this.searchGarbage()
              }else{
                wx.showToast({
                  title: '说话太小声啦',
                  icon:'error',
                  duration:1500
                })
              }
            },
            fail:(err => {
              wx.showToast({
                title: '语音识别失败',
                icon:'error',
                duration:1500
              })
            })
            
          })
        }
      })
    })
  },
  //进入拍照页面前先检测是否有权限启用摄像头
  toCamera(){
    wx.getSetting({
      success:(res) => {
        console.log(res);
        const scopeCamera = res.authSetting['scope.camera']
        if(scopeCamera){
          wx.navigateTo({
            url: '../camera/camera',
          })
        }else{
          wx.authorize({
            scope: 'scope.camera',
            success:((res) => {
              wx.navigateTo({
                url: '../camera/camera',
              })
            }),
            fail:((err) => {
              wx.showModal({
                title:'没有权限',
                content:'体验该功能需要您授权功能权限，请前往设置开启'
              })
            })
          })
        }
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})